from decimal import Decimal

from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware

from app.api.admin.admin_api import admin_api_router
from app.api.v1.api import api_router
from app.core.config import settings
from app.core.exceptions import AppException
from app.core.logger import logger
from app.db.session import engine
from app.models.base import Base
from app.utils.response import error_response

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title=settings.PROJECT_NAME,
    description=settings.PROJECT_DESC,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    json_encoders={Decimal: str}

)

# 设置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 修改 main.py 中的 validation_error_handler
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
    first_error = exc.errors()[0]
    error_message = first_error["msg"]
    if first_error['type'] == 'missing':
        param_name = first_error["loc"][-1]
        logger.error("**************************************")
        logger.error(param_name)
        logger.error("**************************************")
        error_message = f"必填参数「{param_name}」不能为空"
        data = {"param": param_name}
    else:
        data = {}

    # 直接返回error_response的结果（已为JSONResponse）
    return error_response(
        status_code=400,
        message=error_message,
        data=data
    )


# 全局异常处理
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
    return error_response(
        status_code=exc.status_code,
        message=exc.message,
        data=exc.data
    )


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    # 记录异常日志
    import logging
    logging.error(f"未捕获的异常: {str(exc)}", exc_info=True)
    return error_response(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        message="服务器内部错误",
        data=str(exc) if settings.ENVIRONMENT == "development" else None
    )


# 注册路由
app.include_router(api_router)
app.include_router(admin_api_router)


@app.get("/")
async def root():
    return {
        "message": f"欢迎使用 {settings.PROJECT_NAME}",
        "docs_url": f"/docs",
        "redoc_url": f"/redoc"
    }


if __name__ == "__main__":
    import uvicorn

    logger.info("Starting application with Uvicorn")
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
